package cn.beecode.zookeeper.demo;

import java.io.IOException;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZKCreate {
	public static void main(String[] args) throws IOException, KeeperException, InterruptedException{
		final ZooKeeper zk = new ZooKeeper("10.2.9.59:2181", 50000, new Watcher(){

			public void process(WatchedEvent event) {
				// TODO Auto-generated method stub
				System.out.println(event.getState());
	
			}
		
		});
		
		zk.create("/leaderlatch", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
		//zk.close();
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,5);
		CuratorFramework curator = CuratorFrameworkFactory.newClient("10.2.9.59:2181", retryPolicy);
		
		LeaderLatch leaderLatch = new LeaderLatch(curator, "/leaderlatch", "part1");
		
		leaderLatch.addListener(new LeaderLatchListener(){

			public void isLeader() {
				// TODO Auto-generated method stub
				System.out.println("I am leader");
			}

			public void notLeader() {
				// TODO Auto-generated method stub
				System.out.println("I am not leader");
			}
			
		});
		
		curator.start();
		try {
			leaderLatch.start();
			leaderLatch.await();
			leaderLatch.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		curator.close();
	}
}
